<?php
FLEA::loadClass('Api_Session');
class Api_Lib_Rsp_Login extends Api_Session{

    function __construct() {
        $this->_model = FLEA::getSingleton('Model_Login');
        $this->login_type = '';
        //根域名
        $baseUrlstr = detect_uri_base();
        $this->serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));
    }

    //组织传回的数据
    function formatUser($mobile ,$member){
        if(!$member && $mobile){
            $condition = array();
            $condition['phone'] = $mobile;
            $member = $this->_model->find($condition);
        }

        //组织返回数据
        $user             = array();
        $user['userId']   = $member['id'];
        $user['userName'] = strval($member['userName']);
        $user['realName'] = strval($member['realName']);
        $user['mobile']   = strval($member['phone']);
        $user['headerImg'] = $this->serverUrl.'Resource/Image/App/header.png';
        if($this->login_type == 'weixin'){
            $user['openid']   = strval($member['openid']);
            $user['unionid']  = strval($member['unionid']);
        }else{
            //如果是登录成功的，则开始一个sid
            // $user['sid']  = $this->setSid();
        }


        return $user;
    }

    /**
     * 登录验证
     * Time：2019/07/17 14:17:33
     * @author
    */
    function login($params = array(),& $service){
        $this->login_type = $params['provider'];
    }

    /**
     * 登录验证：手机验证码登录
     * 如果对方没有注册，则直接注册一个个人账号
     * Time：2019/07/17 14:17:33
     * @author
    */
    function loginMobile($params = array(),& $service){
        if(!isset($params['vcode']) || !isset($params['mobile'])){
            // $service->send_user_error('error' ,'params error');
            return array('success'=>false,'msg'=>'参数丢失');
        }

        $this->login_type = $params['provider'];

        //查找验证码是否存在
        $smsVerify = FLEA::getSingleton('Api_Lib_Rsp_Sms');
        $verifyRes = $smsVerify->verifyVcode($params);
        if(!$verifyRes['status']){
            return array('success'=>false,'msg'=>'验证码不正确');
        }

        //查找手机号是否已是会员
        $condition = array();
        $condition['mobile'] = $params['mobile'];
        $member = $this->_model->find($condition);
        if(!$member['id']){
            //注册一个账号，自动注册
            $data = array(
                'mobile'     => $params['mobile'],
                'memberName' => $params['mobile'],
                'type'       => 'person',
                'sex'        => 'unknown',
                'createTime' => date('Y-m-d H:i:s'),
                'openid'     => strval($params['openid']),
            );
            $id = $this->_model->save($data);
            if(!$id){
                return array('success'=>false,'msg'=>'登录失败');
            }
        }else{
            //如果是微信登录的，则进行绑定openid，如果重复绑定的，不处理
            if($params['openid'] && !$member['openid']){
                $data = array(
                    'id'     => $member['id'],
                    'openid' => strval($params['openid']),
                );
                $this->_model->save($data);
            }
        }

        //组织返回数据
        $user = $this->formatUser($params['mobile']);

        return array('success'=>true,'msg'=>'登录成功','userinfo'=>$user);
    }

    /**
     * 用户密码登录
     * Time：2020/04/29 08:50:58
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function loginUserName($params = array(),& $service) {
        if(!isset($params['username']) || !isset($params['passwd'])){
            return array('success'=>false,'msg'=>'参数丢失');
        }

        $this->login_type = $params['provider'];

        //查找是否有用户，进行验证
        $user = $this->_model->findByUsername($params['username']);
        if (!$user) {
            return array('success'=>false,'msg'=>'无效用户名');
        }

        if(_md5($params['passwd'])!=$user['passwd']) {
            return array('success'=>false,'msg'=>'无效密码');
        }

        $res = $this->_model->changeLoginTime($user['id']);
        //如果是微信登录的，则进行绑定openid，如果重复绑定的，不处理
        if($params['openid'] && !$user['openid']){
            $data = array(
                'id'     => $user['id'],
                'openid' => strval($params['openid']),
            );
            $this->_model->save($data);
        }
        $user = $this->_model->findByUsername($params['username']);
        //组织返回数据
        $userFormat = $this->formatUser($params['phone'] ,$user);

        return array('success'=>true,'msg'=>'登录成功','userinfo'=>$userFormat);
    }

    /**
     * 登录验证
     * Time：2019/07/17 14:17:33
     * @author
    */
    function loginout($params = array(),& $service){
        //退出登录
        if($params['openid'] && $params['provider'] == 'weixin'){
            $user = $this->_model->find(array('openid'=>$params['openid']));
            if($user['id']){
                $data = array(
                    'id'       =>$user['id'],
                    'openid'   =>'',
                    'unionid'  =>'',
                    'nickname' =>'',
                );
                $this->_model->update($data);
            }
        }else if($params['sid']){
            $this->sessionDestory($params['sid']);
        }

        return array('success'=>true,'msg'=>'安全退出成功');
    }

    /**
     * mp小程序登录验证，一般会传递小程序的一些个人信息过来
     * Time：2019/11/22 09:25:58
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function loginMp($params = array(),& $service){
        if(!$params['userinfo']){
            $service->send_user_error('param userinfo not found');
        }

        //把json转换
        $userinfo = json_decode($params['userinfo'],true);

        if(!is_array($userinfo)){
            $service->send_user_error('param userinfo error');
        }

        $provider = $params['provider'] ? $params['provider'] : 'weixin';
        if(strtolower($provider) == 'weixin'){
            $result = $this->loginBywxcode($userinfo ,$params);
        }

        return $result;
    }

    /**
     * 微信code认证登录
     * Time：2019/11/22 09:33:36
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function loginBywxcode($userinfo ,$params){
        if(!$userinfo['code']){
            return array('openid'=>'','msg'=>'code null');
        }

        //获取微信code对应的openid
        $wxService = FLEA::getSingleton('Api_WxCode2info');
        $openid = $wxService->code2openid($userinfo['code'] ,true);
        $this->login_type = 'weixin';

        $user = array(
            'openid'   => strval($openid['body']['openid']),
            'unionid'  => strval($openid['body']['unionid']),
            'msg'      => strval($openid['body']['errmsg']),
            'errcode'  => strval($openid['body']['errcode']),
            'nickname' => strval($params['nickname']),
            'userId'   => '',
            'userName' => '',
            'realName' => '',
            'compName' => '',
        );

        //查找openid对应的用户表是否有账户
        if($user['openid']){
            $sql = "SELECT * from acm_userdb where openid = '{$user['openid']}'";
            $uLocal = $this->_model->findBySql($sql);
            $uLocal = $uLocal[0];
            if($uLocal){
                $user = $this->formatUser($uLocal['mobile'], $uLocal);
            }
        }

        return array(
            'userinfo'=>$user
        );
    }

    /**
     * 绑定erp的二维码
     * Time：2019/11/22 13:27:02
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function bindMpCode($params = array(),& $service){
        $time = time();
        $openid = strval($params['openid']);
        $nickname = strval($params['nickname']);
        if(!$openid){
            return array('msg'=>'微信身份参数缺失','success'=>false);
        }

        $param = json_decode($params['code'] ,1);
        //有效期是120秒，如果是测试帐号给微信审核的，需要时间长点，防止无法审核
        $expires_in_qr = 120;
        if($param['test'] && $param['test']=='eqinfo'){
            $expires_in_qr = 5*24*3600;//5天有效期
        }
        if(($time - $param['timestamp']) > $expires_in_qr ){
            return array('msg'=>'二维码过期,时效两分钟','success'=>false);
        }

        if(!$param['uid'] || !$param['uname']){
            return array('msg'=>'账户信息有误','success'=>false);
        }

        //验证内容否合法
        $class = FLEA::getSingleton('Controller_App_Mp');
        $localToken = $class->tokenFormat($param);
        if($localToken != $param['token']){
            return array('msg'=>'二维码信息不合法','success'=>false);
        }

        //判断uid和uname是否匹配
        $user = $this->_model->findByUsername($param['uname']);
        if(!$user || $user['id'] != $param['uid']){
            return array('msg'=>'用户信息不匹配','success'=>false);
        }

        //如果该openid已经绑定了其他帐号，则提示不能绑定多个帐号
        $condition = array();
        $condition['openid'] = $openid;
        $condition[] = array('id',$user['id'] ,'<>');
        $count = $this->_model->findCount($condition);
        if($count > 0 ){
            return array('msg'=>'该微信已绑定其他帐号,不能绑定多个','success'=>false);
        }

        //如果已经被绑定并且布匹配，不能再次绑定
        if($user['openid'] !='' && $user['openid'] != $openid){
            return array('msg'=>'该账号已经绑定,不能重复绑定','success'=>false);
        }

        //进行绑定到账号的操作，直接保存
        $data = array(
            'id'       => $user['id'],
            'openid'   => $openid,
            'nickname' => $nickname,
        );
        $res = $this->_model->update($data);

        $class = FLEA::getSingleton('TMIS_Controller');
        $compName = $class->getCompName();

        return array('success'=>true,'msg'=>'绑定完成','userinfo'=>array(
            'userId'   =>$user['id'],
            'userName' =>$user['userName'],
            'compName' =>$compName,
            'openid'   =>$openid,
            'nickname' =>$nickname,
            'realName' =>$user['realName'],
        ));
    }

    /**
     * 获取菜单
     * Time：2019/11/25 13:57:38
     * @author li
     * @param 参数类型
     * @return 返回值类型
    */
    function getMenu($params = array(),& $service){

        $_menu = array(
            array('itemId'=>'ruku','id'=>'100-1','title'=>'样品入库'),
            array('itemId'=>'rukuList','id'=>'100-2','title'=>'入库查询'),
            array('itemId'=>'chuku','id'=>'100-3','title'=>'样品出库'),
            array('itemId'=>'chukuList','id'=>'100-4','title'=>'出库查询'),
            array('itemId'=>'diaoKu','id'=>'100-5','title'=>'库存调整'),
            array('itemId'=>'search','id'=>'100-6','title'=>'扫码找样'),
            array('itemId'=>'product','id'=>'90-4','title'=>'样品档案'),
            array('itemId'=>'client','id'=>'90-5','title'=>'客户档案'),
            array('itemId'=>'kuwei','id'=>'90-6','title'=>'样品库位'),
        );

        //判断有权限的保留，没有权限的去掉菜单项目
        //获取用户信息
        $user = array();
        if($params['openid']){
            $user = $this->_model->find(array('openid'=>$params['openid']));
        }elseif($params['userId']){
            // $user = $this->_model->find(array('id'=>$params['userId']));
        }

        $m = FLEA::getSingleton('Model_Acm_Func');
        $ret = array();
        foreach ($_menu as & $v) {
            $v['leaf'] = true;
            if($user){
                $a = $m->changeVisible($v, array('userName' => $user['userName']));
                if(!$a) continue;
                $ret[] = $a;
            }else{
                $ret[] = $v;
            }
        }


        return array('menu'=>$ret,'menuId'=>array_col_values($ret ,'itemId'));
    }

    //检查是否Openid解绑
    function checkUser($params = array(),& $service){
        $this->login_type = $params['provider'];
        $user = array();
        if($params['openid']){
            $user = $this->_model->find(array('openid'=>$params['openid']));
        }

        return array('success'=>($user['id'] > 0),'userId'=>$user['id']+0,'msg'=>'验证完成');
    }

    //获取用户详细
    function getUser($params = array(),& $service){
        if(!$params['userId']){
            return array('success'=>false,'msg'=>'参数错误UID');
        }

        $this->login_type = $params['provider'];
        $user = $this->_model->find($params['userId']);
        $userinfo = $this->formatUser($user['mobile'] ,$user);
        $userinfo['email']       = $user['email'];
        $userinfo['birthday']    = $user['birthday'];
        $userinfo['address']     = $user['address'];
        $userinfo['companyName'] = $user['companyName'];

        // ..处理性别
        $userinfo['sex'] = $this->_model->getSex($user['sex'] ? $user['sex'] : 'unknown');

        return array('success'=>true,'userinfo'=>$userinfo,'msg'=>'');
    }

    //获取用户详情
    function getUserForm($params = array(),& $service){
        if(!$params['userId']){
            return array('success'=>false,'msg'=>'参数错误UID');
        }

        $user = $this->_model->find($params['userId']);

        return array('success'=>true,'userinfo'=>$user);
    }

    //修改用户信息
    function updateUserForm($params = array(),& $service){
        if(!$params['userinfo']){
            return array('success'=>false,'msg'=>'参数错误userinfo');
        }
        $userinfo = json_decode($params['userinfo'] ,1);
        if(!$userinfo['password']){
            return array('success'=>false,'msg'=>'密码不能为空');
        }
        if($userinfo['password']!=$userinfo['passwordConfirm']){
            return array('success'=>false,'msg'=>'两次密码必须一致');
        }

        $data = array(
            'id'     => $userinfo['id'],
            'passwd' => _md5($userinfo['password']),
        );
        $res = $this->_model->update($data);
        return array('success'=>$res,'msg'=>'保存完成');
    }

    //初始化用户信息的时候用到
    function getUserInit(&$params){
        if(!$params['userId']){
            if($params['openid']){
                $condition = array();
                $condition['openid'] = $params['openid'];
                $member = $this->_model->find($condition);
                $params['userId'] = $member['id'];
            }else if($params['sid']){
                //从session中获取
            }
        }
    }
}
?>